// var eventTypes=[
//   "click",
//   "dbClick"
// ]

var eventMixin = {
  _listeners: null,

  //添加监听:将我们监听(回调函数)添加到监听数组中,等待被触发
  on: function(type, listener, once) {
    var listeners = (this._listeners = this._listeners || {}); //保证listener/this._listeners 不为空
    var eventListenrs = (listeners[type] = listeners[type] || []); //保证eventListenrs/listeners[type] 不为空 --数组
    //保证健壮性,不会添加同一样的listener
    for (var i = 0, len = eventListenrs.length; i < len; i++) {
      var el = eventListenrs[i];
      // if(eventTypes.indexof(type)){
      //   this.addeventListener("type",listener);
      // }
      if (el.listener === listener) return;
    }

    eventListenrs.push({ listener: listener, once: once });

    return this;
  },

  //删除监听:将我们监听(回调函数)从监听数组中删除
  off: function(type, listener) {
    //如果参数为空,则把所有的删除===把监听数组清空(设成null)
    if (arguments.length === 0) {
      this._listeners = null;
      return this;
    }

    var eventListenrs = this._listeners && this._listeners[type];

    if (eventListenrs) {
      //如果参数为1个(参数表明的是事件类型),把给类型的监听全部删除
      if (arguments.length == 1) {
        delete this._listeners[type];
        return this;
      }

      //如果参数为两个,则寻找该类型和监听器都对应上那个监听,然后删除
      for (var i = 0, len = eventListenrs.length; i < len; i++) {
        var el = eventListenrs[i];
        if (el.listener === listener) {
          eventListenrs.splice(i, 1);
          if (eventListenrs.length === 0) delete this._listeners[type];
          break;
        }
      }
    }
    return this;
  },

  //触发:从监听数组中查询到相应的监听,然后触发监听(调用这个函数)
  fire: function(type, detail) {
    var event, eventType;
    //如果传入的参数type是字符串,则这个type指的是事件的类型
    //如果传入的参数type是对象,则这个type指的是事件对象
    if (typeof type === "string") {
      eventType = type;
    } else {
      event = type;
      eventType = type.type;
    }

    var listeners = this._listeners;
    if (!listeners) return false;

    var eventListenrs = listeners[eventType];
    if (eventListenrs) {
      var eventListenrsCopy = eventListenrs.slice(0); //复制
      event = event || new EventObject(eventType, this, detail);
      if (event._stopped) return false;
      for (var i = 0; i < eventListenrsCopy.length; i++) {
        var el = eventListenrsCopy[i];
        el.listener.call(this, event); //调用
        //如果监听的once是true,则表示只执行一次,执行完后删除
        if (el.once) {
          var index = eventListenrs.indexOf(el);
          if (index > -1) {
            eventListenrs.slice(index, 1);
          }
        }
      }

      if (eventListenrs.length === 0) delete listeners[eventType];
      return true;
    }

    return false;
  }
};

//
var EventObject = Class.create({
  constructor: function EventObject(type, target, detail) {
    this.type = type;
    this.target = target;
    this.detail = detail;
    this.timeStamp = new Date();
  },
  type: null,
  target: null,
  detail: null,
  timeStamp: null
});
